/*
 * usertask.c
 *
 *  Created on: 2020年10月28日
 *      Author: Tao
 */
#include <string.h>

#include "user_task.h"
#include "user.h"
#include "main.h"
#include "cmsis_os.h"

#include "sht2x_for_stm32_hal.h"
#include "adc_ext_user.h"
//#include "trcRecorder.h"

//任务句柄
TaskHandle_t StartTask_Handler;
TaskHandle_t LED0Task_Handler;
TaskHandle_t ModbusPollTask_Handler;
#ifdef ADS1115
TaskHandle_t ADS1115DaqTask_Handler;
#endif

TaskHandle_t McuAdcDaqTask_Handler;

TaskHandle_t MBRefreshTask_Handler;
TaskHandle_t CC1101Config_Handler;
TaskHandle_t DHT11DaqTask_Handler;
TaskHandle_t StorableDataSaveTask_Handler;
TaskHandle_t LimitSwitchMonitorTask_Handler;
TaskHandle_t IwdgTask_Handler;

//事件组
EventGroupHandle_t xCreatedEventGroup;

void FreeRTOS_Exec()
{
    //#if (TRC_CFG_RECORDER_MODE == TRC_RECORDER_MODE_STREAMING)
    //	// Getting Started with Tracealyzer for FreeRTOS – Streaming Mode
    ////	vTraceEnable(TRC_INIT);
    //#elif (TRC_CFG_RECORDER_MODE == TRC_RECORDER_MODE_SNAPSHOT)
    //	// Getting Started with Tracealyzer for FreeRTOS – Snapshot Mode
    ////	vTraceEnable(TRC_START);
    //#else
    //
    //#endif

    //创建开始任务
    xTaskCreate((TaskFunction_t) start_task,			 //任务函数
            (const char*) "start_task",			 //任务名称
            (uint16_t) START_STK_SIZE,			 //任务堆栈大小
            (void*) NULL,						 //传递给任务函数的参数
            (UBaseType_t) START_TASK_PRIO,		 //任务优先级
            (TaskHandle_t*) &StartTask_Handler); //任务句柄

    //	vTaskStartScheduler(); //开启任务调度
}

//开始任务任务函数
void start_task(void *pvParameters)
{
    //	xCreatedEventGroup = xEventGroupCreate(); //创建事件组

    taskENTER_CRITICAL(); //进入临界区

    //创建监控任务
    //	xTaskCreate((TaskFunction_t)Iwdg_task,
    //				(const char *)"Iwdg_task",
    //				(uint16_t)IWDGTASK_STK_SIZE,
    //				(void *)NULL,
    //				(UBaseType_t)IWDGTASK_TASK_PRIO,
    //				(TaskHandle_t *)&IwdgTask_Handler);

    //创建LED0任务
    int result_0 = xTaskCreate((TaskFunction_t) led0_task, (const char*) "led0_task", (uint16_t) LED0_STK_SIZE, (void*) NULL, (UBaseType_t) LED0_TASK_PRIO, (TaskHandle_t*) &LED0Task_Handler);

    //	//创建modbus poll任务
    //	xTaskCreate((TaskFunction_t)ModbusPoll_task,
    //				(const char *)"ModbusPoll_task",
    //				(uint16_t)MODBUS_POLL_STK_SIZE,
    //				(void *)NULL,
    //				(UBaseType_t)MODBUS_POLL_TASK_PRIO,
    //				(TaskHandle_t *)&ModbusPollTask_Handler);

#ifdef ADS1115
    //创建ads1115 DAQ任务
    xTaskCreate((TaskFunction_t)ADS1115Daq_task,
            (const char *)"ADS1115Daq_task",
            (uint16_t)ADS1115_DAQ_STK_SIZE,
            (void *)NULL,
            (UBaseType_t)ADS1115_DAQ_TASK_PRIO,
            (TaskHandle_t *)&ADS1115DaqTask_Handler);
#endif

    //创建on-chip ADC DAQ任务
    int result_1 = xTaskCreate((TaskFunction_t) McuAdcDaq_task, (const char*) "McuAdcDaq_task", (uint16_t) MCU_ADC_DAQ_STK_SIZE, (void*) NULL, (UBaseType_t) MCU_ADC_DAQ_TASK_PRIO,
            (TaskHandle_t*) &McuAdcDaqTask_Handler);

    //	//创建刷新modbus寄存器执行动作的任务
    //	xTaskCreate((TaskFunction_t)MBRefresh_task,
    //				(const char *)"MBRefresh_task",
    //				(uint16_t)MBREFRESHTASK_STK_SIZE,
    //				(void *)NULL,
    //				(UBaseType_t)MBREFRESHTASK_TASK_PRIO,
    //				(TaskHandle_t *)&MBRefreshTask_Handler);

    //创建配置CC1101通讯参数的任务
    int result_3 = xTaskCreate((TaskFunction_t) WSN31Config_task, (const char*) "CC1101Config_task", (uint16_t) CC1101CONFIGTASK_STK_SIZE, (void*) NULL, (UBaseType_t) CC1101CONFIGTASK_TASK_PRIO,
            (TaskHandle_t*) &CC1101Config_Handler);

    //	//创建DHT11传感器配置与数据读取任务
    //	xTaskCreate((TaskFunction_t)DHT11Daq_task,
    //				(const char *)"DHT11Daq_task",
    //				(uint16_t)DHT11DAQ_TASK_STK_SIZE,
    //				(void *)NULL,
    //				(UBaseType_t)DHT11DAQ_TASK_PRIO,
    //				(TaskHandle_t *)&DHT11DaqTask_Handler);

    //创建Storable Data数据存储管理
    //	xTaskCreate((TaskFunction_t )StorableDataSave_task,
    //			(const char*    )"StorableDataSave_task",
    //			(uint16_t       )STORABLEDATASAVE_TASK_STK_SIZE,
    //			(void*          )NULL,
    //			(UBaseType_t    )STORABLEDATASAVE_TASK_PRIO,
    //			(TaskHandle_t*  )&StorableDataSaveTask_Handler);

    //	//创建光电对管限位开关的监控任务
    //	xTaskCreate((TaskFunction_t)LimitSwitchMonitor_task,
    //				(const char *)"LimitSwitchMonitor_task",
    //				(uint16_t)LIMITSWITCHMONITOR_TASK_STK_SIZE,
    //				(void *)NULL,
    //				(UBaseType_t)LIMITSWITCHMONITOR_TASK_PRIO,
    //				(TaskHandle_t *)&LimitSwitchMonitorTask_Handler);

    vTaskDelete(StartTask_Handler); //删除开始任务
    taskEXIT_CRITICAL();			//退出临界区
}

///**
// * @brief 独立硬件看门狗喂狗任务
// *      只有监控的任务都在指定的时间被执行，事件组全部置位后，才能进行喂狗。
// *      因此监控的任务异常或者停止执行时，硬件看门狗会自动重启系统，以尝试恢复。
// *      本项目中 监控的任务有：ModbusPoll_task，McuAdcDaq_task，MBRefresh_task
// * @param pvParameters
// */
//void Iwdg_task(void *pvParameters)
//{
//	EventBits_t uxBits;
//	const TickType_t xTicksToWait = 2000 / portTICK_PERIOD_MS; /* 最大延迟2000ms */
//
//	IWDG_Config(IWDG_Prescaler_64, 625 * 5); // timeout = 5s
//
//	while (1)
//	{
//		/* 等待所有任务发来事件标志 */
//		uxBits = xEventGroupWaitBits(xCreatedEventGroup, /* 事件标志组句柄 */
//									 TASK_BIT_ALL,		 /* 等待TASK_BIT_ALL被设置 */
//									 pdTRUE,			 /* 退出前TASK_BIT_ALL被清除，这里是TASK_BIT_ALL都被设置才表示“退出”*/
//									 pdTRUE,			 /* 设置为pdTRUE表示等待TASK_BIT_ALL都被设置*/
//									 xTicksToWait);		 /* 等待延迟时间 */
//
//		if ((uxBits & TASK_BIT_ALL) == TASK_BIT_ALL) //判断各个任务是否执行
//		{
//			IWDG_ReloadCounter(); // 喂狗
//		}
//	}
//}

// LED0任务函数
void led0_task(void *pvParameters)
{
    TickType_t ticks = xTaskGetTickCount();

    while (1)
    {
        HAL_GPIO_TogglePin(MCU_LED_CTRL_GPIO_Port, MCU_LED_CTRL_Pin);
        //		vTaskDelay(250);
        vTaskDelayUntil(&ticks, 250);
    }
}


void McuAdcDaq_task(void *pvParameters)
{
    ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
    is_BLE_configured = 1;
    TickType_t ticks = xTaskGetTickCount();

    while (1)
    {
        User_RefreshData();
        User_SendDeviceStatus();
        //		xEventGroupSetBits(xCreatedEventGroup, TASK_BIT_2);
        // 200ms 一个处理周期
        vTaskDelayUntil(&ticks, 100);
    }
}

void WSN31Config_task(void *pvParameters)
{

    /// Set baud rate to 115200 of BLE for the initial state
    /// This setting can only be valided when the BLE baud rate is 9600
    is_BLE_configured = 0;

    HAL_UART_Transmit(&HAL_USART_BLE, BLE_CMD_SET_BAUDRATE"115200", 14, 100);
    osDelay(1000);

    /// Restore the USART3 to 115200 bps
    /// We need to deinit the usart and then reconfig it,
    /// Because when calling HAL_UART_Init function, it will call the HAL_UART_MspInit function
    /// That would lead something wrong, e.g., the DMA transmission could be work in wrong state
    HAL_UART_DeInit(&HAL_USART_BLE);
    MX_USART3_UART_Init_115200();
    __HAL_UART_ENABLE_IT(&HAL_USART_BLE, UART_IT_IDLE);
    HAL_UART_Receive_DMA(&HAL_USART_BLE, usart3_RecvBuff, USART3_RECVBUFF_SIZE);

    // set name of the BLE
    HAL_UART_Transmit(&HAL_USART_BLE, BLE_CMD_SET_NAME, strlen(BLE_CMD_SET_NAME), 100);
    HAL_UART_Transmit(&HAL_USART_BLE, device_info.name, strlen(device_info.name), 100);
    osDelay(1000);

    // set the radio power to +4dBm
    HAL_UART_Transmit(&HAL_USART_BLE, "TTM:TPL-(+4)", 14, 100);
    osDelay(1000);

    taskENTER_CRITICAL(); //进入临界�???

    xTaskNotifyGive(McuAdcDaqTask_Handler);
    vTaskDelete(NULL); //删除任务

    taskEXIT_CRITICAL();			//�???出临界区
}
